package com.sjz.ctkj.canvasstudy;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;

import com.sjz.ctkj.canvasstudy.internetmanage.ReqestUrl;
import com.sjz.ctkj.canvasstudy.utils.ShareUtils;
import com.sjz.ctkj.canvasstudy.utils.SysUtils;
import com.sjz.ctkj.canvasstudy.utils.SystemUtil;
import com.sjz.ctkj.canvasstudy.utils.ToastUtils;
import com.sjz.ctkj.canvasstudy.utils.UpdateAppHttpUtil;
import com.sjz.ctkj.canvasstudy.utils.ZXingUtils;
import com.sjz.ctkj.canvasstudy.utils.ZipUtils;
import com.sjz.ctkj.canvasstudy.weghit.MarqueeTextviewNofocus;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import okhttp3.Call;

/**
 * 空间一
 */
public class SpaceFirstActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView isnotintenert_tv,download_progrees;
    private boolean isSHowImei=false;
    String imei="";
    private ShareUtils shareUtils;
    private MarqueeTextviewNofocus upTextView ;

    private MarqueeTextviewNofocus downTextView ;

    private ImageView imageView ;

    private VideoView videoView;
    private MediaController localMediaController=null;
    private String palyeUrl="";//播放路径

    private String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/adscreen/myzip";//下载文件的存储绝对路径
    private String unZipPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/adscreen/usezip";//解压的zip文件路径
    private String unZipPath2 = Environment.getExternalStorageDirectory().getAbsolutePath() + "/adscreen/usezip2";
    String fileName = "adscreen.zip";//文件名称【应该动态获取，此处测试，所以写死即可】

    String codePath="";//二维码路径
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.space_first);
        shareUtils=new ShareUtils(this);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        hideBottomUIMenu();//隐藏虚拟按键
        registBrocatRciver();//注册广播通知
        imei= SystemUtil.ID();//获取设备号
        // 调用 Handler 来异步设置别名
        if(!"1".equals(shareUtils.getTag())){
            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, imei));
            addJpshTag(imei);
        }
        initView();
        if(shareUtils.getHtmlUrl()!=null&&!"".equals(shareUtils.getHtmlUrl())){
            isnotintenert_tv.setBackgroundColor(getResources().getColor(R.color.transfle));
            isnotintenert_tv.setGravity(Gravity.RIGHT);
            isnotintenert_tv.setText("");
            createEWMImg(shareUtils.getCodePath());
            parsetViewPathByHtml(shareUtils.getHtmlUrl());
            initVedioPlayer(palyeUrl);
        }else{
            isnotintenert_tv.setBackgroundColor(getResources().getColor(R.color.white));
            isnotintenert_tv.setGravity(Gravity.CENTER);
        }

    }

    private void initView(){
        videoView = findViewById(R.id.videoView);
        upTextView = findViewById(R.id.upTextView);
        downTextView = findViewById(R.id.downTextView);
        imageView = findViewById(R.id.imageView);
        isnotintenert_tv=(TextView)this.findViewById(R.id.isnotintenert_tv);
        isnotintenert_tv.setOnClickListener(this);
        isnotintenert_tv.setText(imei);
        download_progrees=(TextView)this.findViewById(R.id.download_progrees);
        download_progrees.setVisibility(View.GONE);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.isnotintenert_tv:
                if(isSHowImei){
                    isnotintenert_tv.setText(imei);
                    isSHowImei=false;
                }else{
                    isSHowImei=true;
                    isnotintenert_tv.setText("");
                }
                break;
        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu(){
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    /**
     * 生成二维码
     * @param erwurl
     */
    public void createEWMImg(String erwurl){
        Bitmap h = ZXingUtils.createQRCodeBitmap(erwurl, 800, 800, "UTF-8", "H", "1", Color.BLACK, Color.WHITE);
        imageView.setImageBitmap(h);
    }


    public MyBrocatRecicer myBrocatRecicer;
    public void registBrocatRciver(){
        myBrocatRecicer=new MyBrocatRecicer();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ReqestUrl.REQUEST_DOWNLOAD_ZIP);
        filter.addAction(ReqestUrl.REQUEST_DOWNLOAD_VERSION);
        registerReceiver(myBrocatRecicer,filter);
    }
    class MyBrocatRecicer extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(ReqestUrl.REQUEST_DOWNLOAD_ZIP)){
                downloadFile(intent.getStringExtra("value"));
                codePath=intent.getStringExtra("codePath");
            }else if(intent.getAction().equals(ReqestUrl.REQUEST_DOWNLOAD_VERSION)){
                updateVersion();
//                if(isRoot()){
//                    downloadAPK("http://tomcat.xzcysoft.com/zjj/adscreen.apk");
//                }else{
//
//                }
            }
        }
    }
    //下载压缩包
    public void downloadFile(String url){
        ToastUtils.popUpToast("开始下载压缩包" );
        download_progrees.setVisibility(View.VISIBLE);
        OkHttpUtils.get()
                .url(url)
                .tag(this)
                .build()
                .execute(new FileCallBack(savePath,fileName) {

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtils.popUpToast("下载zip失败");
                        download_progrees.setVisibility(View.GONE);
                    }
                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        download_progrees.setText((int) (100 * progress)+"%");
                    }
                    @Override
                    public void onResponse(File downloadFile, int id) {
                        download_progrees.setVisibility(View.GONE);
                        try {
                            File file = new File(savePath+"/"+fileName);
                            if(file.exists()){
                                ToastUtils.popUpToast("下载成功" );
                                myHandler.sendEmptyMessage(200);
//                                Utils.upZipFile(file, unZipPath,myHandler);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
    }
    public Handler myHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 100:
                    reshHtmlUrl();//刷新url
                    break;
                case 200://解压文件
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                if("1".equals(shareUtils.getDeleteUp())){//如果html路径不是空就解压到第2个文件夹
                                    ZipUtils.UnZipFolder(savePath+"/"+fileName,unZipPath2,myHandler);
                                }else{//如果html路径是空就解压到第1个文件夹
                                    ZipUtils.UnZipFolder(savePath+"/"+fileName,unZipPath,myHandler);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }).start();
                    break;
                case 300:
                    download_progrees.setVisibility(View.VISIBLE);
                    download_progrees.setText("解压："+msg.obj+"%");
                    break;
            }
        }
    };
    public void reshHtmlUrl(){
        isnotintenert_tv.setBackgroundColor(getResources().getColor(R.color.transfle));
        isnotintenert_tv.setGravity(Gravity.RIGHT);
        isnotintenert_tv.setText("");
        shareUtils.setCodePath(codePath);
        createEWMImg(codePath);
        String showUlr="";
        if("1".equals(shareUtils.getDeleteUp())){//如果html路径不是空就解压到第2个文件夹
            shareUtils.setDeleteUp("0");
            showUlr= unZipPath2+"/adscreen/";//adscreen/
        }else {//如果html路径是空就解压到第1个文件夹
            shareUtils.setDeleteUp("1");
            showUlr = unZipPath + "/adscreen/";
        }
        File file = new File(showUlr+"start.html");
        if(file.exists()){
            download_progrees.setVisibility(View.GONE);
            if("1".equals(shareUtils.getDeleteUp())){
                //说明是第一次 需要初始化视频控件
                parsetViewPathByHtml(showUlr);
                initVedioPlayer(palyeUrl);
            }else{
                parsetViewPathByHtml(showUlr);
                alterVedioPath(palyeUrl);
            }
            shareUtils.setHtmlUrl(showUlr);
        }else{

        }

        File delefile = new File(savePath+"/"+fileName);
        if(delefile.exists()){
            Utils.deleteDir(delefile);
        }
        if("1".equals(shareUtils.getDeleteUp())){//如果是1删除unziopath2
            File delefile2 = new File(unZipPath2);
            if(delefile2.exists()){
                Utils.deleteAllDir(unZipPath2);
            }
        }else{
            File delefile3 = new File(unZipPath);
            if(delefile3.exists()){
                Utils.deleteAllDir(unZipPath);
            }
        }
    }

    //通过html获取播放视频路径，并设置轮播图字
    private void parsetViewPathByHtml(String intentHtmlUrl){
        //上下文字
        String s = intentHtmlUrl + "start.html";
        Document document = null;
        try {
            document = Jsoup.parse(new File(s),"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        Elements b = document.getElementsByTag("B");
        String firstTest = b.get(0).text();

        upTextView.setText(firstTest);
        // 初始化
        upTextView.init(getWindowManager());
        // 设置滚动方向
        upTextView.setScrollDirection(MarqueeTextviewNofocus.RIGHT_TO_LEFT);
        // 设置滚动速度
        upTextView.setScrollMode(MarqueeTextviewNofocus.SCROLL_FAST);
        String twoTest = b.get(1).text();

        downTextView.setText(twoTest);
        // 初始化
        downTextView.init(getWindowManager());
        // 设置滚动方向
        downTextView.setScrollDirection(MarqueeTextviewNofocus.RIGHT_TO_LEFT);
        // 设置滚动速度
        downTextView.setScrollMode(MarqueeTextviewNofocus.SCROLL_FAST);
        //获取视频地址
        String mp4Name = document.getElementById("vd").attr("src");
        //播放视频
        palyeUrl="file://"+intentHtmlUrl+mp4Name;
    }
    //初始化播放器
    public void initVedioPlayer(String palyPath){
        localMediaController = new MediaController(this);
        localMediaController.setVisibility(View.GONE);//影藏播放进度条
        videoView.setMediaController(localMediaController);
        videoView.setVideoPath(palyPath);
        //循环播放
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
                mp.setLooping(true);
            }
        });
    }

    //更换视频播放地址
    public void alterVedioPath(String path){
        if(videoView!=null&&videoView.isPlaying()){
            videoView.pause();
        }else{
            initVedioPlayer(path);
        }
        videoView.setVideoPath(path);
        videoView.start();
    }

    //下载apk
    private String apkPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/adscreen";
    String apkName = "adscreen.apk";//文件名称【应该动态获取，此处测试，所以写死即可】
    public void downloadAPK(String url){
        OkHttpUtils.get()
                .url(url)
                .tag(this)
                .build()
                .execute(new FileCallBack(apkPath,apkName) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtils.popUpToast("失败");
                    }
                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                    }
                    @Override
                    public void onResponse(File downloadFile, int id) {
                        try {
                            File file = new File(apkPath+"/"+apkName);
                            if(file.exists()){
//                                Utils.upZipFile(file, unZipPath,myHandler);
//                              install(apkPath+"/"+apkName);
                                if( silentInstall(apkPath+"/"+apkName)){
                                    ToastUtils.popUpToast("程序静默安装已成功，不知道自动打开了吗 看下！");
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    //静默更新程序
    public static boolean silentInstall(String apkPath) {
        boolean result = false;
        DataOutputStream dataOutputStream = null;
        BufferedReader errorStream = null;
        BufferedReader successStream = null;
        Process process = null;
        try {
            // 申请 su 权限
            process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());
            // 执行 pm install 命令
            String command = "pm install -r " + apkPath + "\n";
            dataOutputStream.write(command.getBytes(Charset.forName("UTF-8")));
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();
            errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            StringBuilder errorMsg = new StringBuilder();
            String line;
            while ((line = errorStream.readLine()) != null) {
                errorMsg.append(line);
            }
//            log.debug("silent install error message:{}", errorMsg);
            StringBuilder successMsg = new StringBuilder();
            successStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
            // 读取命令执行结果
            while ((line = successStream.readLine()) != null) {
                successMsg.append(line);
            }
//            log.debug("silent install success message:{}", successMsg);
            // 如果执行结果中包含 Failure 字样就认为是操作失败，否则就认为安装成功
            if (!(errorMsg.toString().contains("Failure") || successMsg.toString().contains("Failure"))) {
                result = true;
            }
        } catch (Exception e) {
//            log.error(e);
        } finally {
            try {
                if (process != null) {
                    process.destroy();
                }
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (errorStream != null) {
                    errorStream.close();
                }
                if (successStream != null) {
                    successStream.close();
                }
            } catch (Exception e) {
                // ignored
            }
        }
        return result;
    }
    //版本升级
    public void updateVersion(){
        new UpdateAppManager
                .Builder()
                //当前Activity
                .setActivity(this)
                //实现httpManager接口的对象
                .setHttpManager(new UpdateAppHttpUtil())
                .dismissNotificationProgress()
                //更新地址
                .setUpdateUrl(ReqestUrl.UPDATEVERSION_URL)
                .setThemeColor(ContextCompat.getColor(this,R.color.tvcolor_13))
                .build()
//                .checkNewApp(new SilenceUpdateCallback());
//                //检测是否有新版本
                .checkNewApp(new UpdateCallback(){
                    @Override
                    protected void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                        String myVersionName = SysUtils.getVersionName(SpaceFirstActivity.this);
                        if(!myVersionName.equals(updateApp.getNewVersion())){
                            updateAppManager.showDialogFragment();
                        }
                    }

                    @Override
                    protected void noNewApp(String error) {
                        super.noNewApp(error);
                    }

                });

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
        if(myBrocatRecicer!=null){
            unregisterReceiver(myBrocatRecicer);
        }
        System.exit(0);
    }
    //============================================注册极光标签======================================================
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
//                    Log.d(TAG, "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
//                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };
    public void addJpshTag(String phone){
        OkHttpUtils
                .post()
                .url(ReqestUrl.ADD_JPUSHTAG_URL)
                .addParams("deviceNo",phone)
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.popUpToast("请求超时");
            }
            @Override
            public void onResponse(String response, int id) {
                if(ReqestUrl.rebacRequestJson(response)!=null){
                }
            }
        });
    }
    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    shareUtils.setTag("1");
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, imei));
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    break;
            }

        }
    };
    //============================================注册极光标签======================================================
}
